//
//  EM_FMDBDataBase.m
//  easymarketing
//
//  Created by mao on 15/12/3.
//  Copyright © 2015年 cubead. All rights reserved.
//

#import "CacheData.h"
#import "FMDatabase.h"

@interface CacheData()
@property (nonatomic, strong) FMDatabase *dataBase;
@end

@implementation CacheData
static CacheData *dataBaseOnce = nil;
+ (CacheData *)sharedDataBase {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataBaseOnce = [[CacheData alloc] init];
    });
    return dataBaseOnce;
}

- (void)createDataBase {
    NSString *path = [NSString stringWithFormat:@"%@/Documents/cacheInfo.rdb", NSHomeDirectory()];
    _dataBase = [[FMDatabase alloc] initWithPath:path];
    //判断数据库是否创建好
    if (_dataBase.open) {
        [self createTable];
    }
}

- (void)requestInitData {

}


- (BOOL)setResponseWithUserName:(NSString *) username andUrl:(NSString *) url andParam:(NSString *) param andHours:(NSInteger) hour andResponse:(id) responses{
    BOOL needRefresh;
    if ([Tools isEmpty:param]) {
        param = @"nil";
    }
    
    NSString *response;
    if ([responses isKindOfClass:[NSArray class]] || [responses isKindOfClass:[NSMutableArray class]]) {
        response = [(NSArray *)responses stringFromObjectArray];
    } else if ([responses isKindOfClass:[NSDictionary class]] || [responses isKindOfClass:[NSMutableDictionary class]]) {
        response = [(NSDictionary *)responses stringFromDictionary];
    } else {
        response = [[responses keyValues] stringFromDictionary];
    }
    NSString *cacheStr = [self getResponseStringWithUserName:username andUrl:url andParam:param];
    if ([cacheStr isEqualToString:response]) {
        needRefresh = NO;
    }
    else {
        needRefresh = YES;
    }
    
    NSString *datetime = [Tools getExpireDateWithHour:hour];
    if (_dataBase.open) {
        BOOL repeat = [self searchTableWithUsername:username andUrl:url andParam:param];
        if (repeat) { //重复就更新
            [self updateTableWithUserName:username andUrl:url andParam:param andDateTime:datetime andResponse:response];
        } else {
            //插入
            NSString *insertSql = @"INSERT INTO appInfo(username,url,param,datetime,response) values(?,?,?,?,?)";
            BOOL isSuc = [_dataBase executeUpdate:insertSql, username, url, param, datetime, response];
            if (isSuc) {
                CMLog(@"插入成功");
            } else {
                CMLog(@"插入失败");
            }
        }
    } else {
        CMLog(@"数据库打开失败");
    }
    return needRefresh;
}

- (NSString *)getResponseStringWithUserName:(NSString *) username andUrl:(NSString *) url andParam:(NSString *)param {
    if ([Tools isEmpty:param]) {
        param = @"nil";
    }
    NSString *select = @"SELECT * FROM appInfo WHERE username = ? AND url = ? AND param = ?";
    FMResultSet *set = [_dataBase executeQuery:select, username, url, param];
    NSString *dateTime;
    while (set.next) {
        dateTime = [set stringForColumnIndex:3];
        BOOL expire = [self isEmpireWithDatetime:dateTime];
        if (expire) {//不过期
            return [set stringForColumnIndex:4];
        }
    }
    return nil;
}


//取数组缓存
- (NSMutableArray *)getArrayResponseWithUserName:(NSString *) username andUrl:(NSString *) url andParam:(NSString *)param andModel:(NSString *)modelName{
    if ([Tools isEmpty:param]) {
        param = @"nil";
    }
    NSString *select = @"SELECT * FROM appInfo WHERE username = ? AND url = ? AND param = ?";
    FMResultSet *set = [_dataBase executeQuery:select, username, url, param];
    NSString *dateTime;
    while (set.next) {
        dateTime = [set stringForColumnIndex:3];
        BOOL expire = [self isEmpireWithDatetime:dateTime];
        if (expire) {//不过期
            return [self arrayfromJson:[set stringForColumnIndex:4] andModel:modelName];
        }
    }
    return [NSMutableArray array];
}

//取字典缓存
- (NSDictionary *)getDictionaryResponseWithUserName:(NSString *)username andUrl:(NSString *)url andParam:(NSString *)param {
    if ([Tools isEmpty:param]) {
        param = @"nil";
    }
    NSString *select = @"SELECT * FROM appInfo WHERE username = ? AND url = ? AND param = ?";
    FMResultSet *set = [_dataBase executeQuery:select, username, url, param];
    NSString *dateTime;
    while (set.next) {
        dateTime = [set stringForColumnIndex:3];
        BOOL expire = [self isEmpireWithDatetime:dateTime];
        if (expire) {//不过期
            return [self dictionaryFromJson:[set stringForColumnIndex:4]];
        }
    }
    return [NSDictionary dictionary];
}

//取model缓存
- (id)getModelResponseWithUserName:(NSString *)username andUrl:(NSString *)url andParam:(NSString *)param andModel:(NSString *)modelName {
    if ([Tools isEmpty:param]) {
        param = @"nil";
    }
    NSString *select = @"SELECT * FROM appInfo WHERE username = ? AND url = ? AND param = ?";
    FMResultSet *set = [_dataBase executeQuery:select, username, url, param];
    NSString *dateTime;
    while (set.next) {
        dateTime = [set stringForColumnIndex:3];
        BOOL expire = [self isEmpireWithDatetime:dateTime];
        if (expire) {//不过期
            return [self modelFromJson:[set stringForColumnIndex:4] withModel:modelName];
        }
    }
    return [[NSClassFromString(modelName) alloc] init];
}

#pragma -mark 数据表操作
//建表
- (void)createTable {
    NSString *createDB = @"CREATE TABLE IF NOT EXISTS appInfo (username text NOT NULL, url text NOT NULL, param text NOT NULL, datetime text NOT NULL, response text NOT NULL)";
    
    BOOL isSuc = [_dataBase executeUpdate:createDB];
    if (isSuc) {
        CMLog(@"表创建成功");
    } else {
        CMLog(@"表创建失败");
    }
}


//查重
- (BOOL)searchTableWithUsername:(NSString *)username andUrl:(NSString *)url andParam:(NSString *)param{
    NSString *select = @"SELECT * FROM appInfo WHERE username = ? AND url = ? AND param = ?";
    FMResultSet *set;
    //加锁，保证线程安全
    //    @synchronized(self) {
    set = [_dataBase executeQuery:select, username, url, param];
    //    }
    while (set.next) {
        return YES;
    }
    
    return NO;
}

//更新
- (void)updateTableWithUserName:(NSString *)username andUrl:(NSString *)url andParam:(NSString *)param andDateTime:(NSString *)datetime andResponse:(NSString *)response {
    NSString *update = @"UPDATE appInfo SET param = ? , datetime = ? , response = ? WHERE username = ? AND url = ?";
    BOOL isSuc = [_dataBase executeUpdate:update, param, datetime, response, username, url];
    if (isSuc) {
        CMLog(@"数据更新成功");
    } else {
        CMLog(@"数据更新失败");
    }
}

#pragma -mark 接口的数据请求





#pragma -mark 工具函数
//比较时间 NO过期， YES不过期
- (BOOL)isEmpireWithDatetime:(NSString *)dateTime {
    NSDate *dateNow = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateTime];
    if (NSOrderedDescending == [dateNow compare:date]) {
        return NO;
    } else {
        return YES;
    }
}

//json转数组
- (NSMutableArray *)arrayfromJson:(NSString *)json andModel:(NSString *)modelName{
    NSArray *array = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSDictionary *dic in array) {
        id model = [[NSClassFromString(modelName) alloc] init] ;
        model = [NSClassFromString(modelName) objectWithKeyValues:dic];
        [mutableArray addObject:model];
    }
    return mutableArray;
}

//json转字典
- (NSDictionary *)dictionaryFromJson:(NSString *)json {
    return [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
}

//json转model
- (id)modelFromJson:(NSString *)json withModel:(NSString *)modelName {
    return [NSClassFromString(modelName) objectWithKeyValues:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil]];
}
@end
